import fs from 'fs';
import path from 'path';
import { WX_MINIPROGRAM_APP_ID, WX_PAY_MCH_ID, WX_PAY_NOTIFY_URL, WX_PAY_PARTNER_KEY, WX_PAY_PFX } from '../../config';
import { md5 } from '../index';

// 初始化微信支付
const WeiXinPay = require('../weixin-pay/index');
const weixinpay = new WeiXinPay({
  appid: WX_MINIPROGRAM_APP_ID,
  mch_id: WX_PAY_MCH_ID,
  partner_key: WX_PAY_PARTNER_KEY,
  pfx: fs.readFileSync(path.join(__dirname, WX_PAY_PFX))
});

/**
 * 统一下单
 * @param payInfo
 * @returns {Promise}
 */
function createUnifiedOrder(payInfo) {
  return new Promise((resolve, reject) => {
    weixinpay.createUnifiedOrder(
      {
        body: payInfo.body,
        out_trade_no: payInfo.out_trade_no,
        total_fee: payInfo.pay_money,
        spbill_create_ip: payInfo.spbill_create_ip,
        notify_url: WX_PAY_NOTIFY_URL,
        trade_type: 'JSAPI',
        openid: payInfo.openid,
        product_id: payInfo.chargeids.join('|')
      },
      (error, result) => {
        // console.log(error, result)
        if (result && result.return_code === 'SUCCESS' && result.return_msg === 'OK') {
          const returnParams = {
            appid: result.appid,
            timeStamp: parseInt(Date.now() / 1000) + '',
            nonceStr: result.nonce_str,
            package: 'prepay_id=' + result.prepay_id,
            signType: 'MD5'
          };
          const paramStr = `appId=${returnParams.appid}&nonceStr=${returnParams.nonceStr}&package=${returnParams.package}&signType=${returnParams.signType}&timeStamp=${returnParams.timeStamp}&key=${WX_PAY_PARTNER_KEY}`;
          returnParams.paySign = md5(paramStr).toUpperCase();
          resolve(returnParams);
        } else {
          console.log('生成微信支付订单失败：', JSON.stringify(result));
          reject(error);
        }
      }
    );
  });
}

/**
 * 生成排序后的支付参数 query
 * @param queryObj
 * @returns {Promise.<string>}
 */
function buildQuery(queryObj) {
  const sortPayOptions = {};
  for (const key of Object.keys(queryObj).sort()) {
    sortPayOptions[key] = queryObj[key];
  }
  let payOptionQuery = '';
  for (const key of Object.keys(sortPayOptions).sort()) {
    payOptionQuery += key + '=' + sortPayOptions[key] + '&';
  }
  payOptionQuery = payOptionQuery.substring(0, payOptionQuery.length - 1);
  return payOptionQuery;
}

export { createUnifiedOrder, buildQuery, weixinpay };
